package com.ywyt.elasticsearch.config;

import org.apache.http.HttpHost;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestClientBuilder;
import org.elasticsearch.client.RestHighLevelClient;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.ArrayList;
import java.util.List;

@Configuration
public class ElasticSearchConfig {
    @Value("${spring.data.elasticsearch.hostAndPort}")
    private String hostAndPort;

    @Bean
    public RestHighLevelClient client(){
        //1.封装HttpHost
        List<HttpHost> hostList = new ArrayList();
        String[] infos = hostAndPort.split(",");
        for (String info : infos) {
            String[] split = info.split(":");
            hostList.add(new HttpHost(split[0],Integer.valueOf(split[1])));
        }
        //2.将hostList转为数组封装到builder中
        RestClientBuilder builder = RestClient.builder(hostList.toArray(new HttpHost[]{}));

        //3.将build传入client中
        RestHighLevelClient client = new RestHighLevelClient(builder);

        return client;
    }
}
